package com.fang.consumer.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.fang.entity.Dept;

@RestController
public class ConsumerDeptController {
	public static final String DEPT_GET_URL = "http://MICROCLOUD-PROVIDER-DEPT-FANG/dept/get/";
	public static final String DEPT_LIST_URL = "http://MICROCLOUD-PROVIDER-DEPT-FANG/dept/list/";
	public static final String DEPT_ADD_URL = "http://MICROCLOUD-PROVIDER-DEPT-FANG/dept/add";
	
	@Resource
	private RestTemplate restTemplate;
	
	@Resource
	private LoadBalancerClient loadBalancerClient;

	@RequestMapping(value = "/consumer/dept/get")
	public Object getDept(long id) {
		ServiceInstance serviceInstance = loadBalancerClient.choose("MICROCLOUD-PROVIDER-DEPT-FANG");
		System.out.println("【serviceInstance】 host = "+serviceInstance.getHost());
		Dept dept = this.restTemplate.getForObject(DEPT_GET_URL + id, Dept.class);
		return dept;
		
	}

	/*
	 * http://localhost/consumer/dept/list 应用之间进行路由的转发restTemplate。
	 * 消费端进行访问，负载均衡到生产者
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/consumer/dept/list")
	public Object listDept() {
		List<Dept> allDepts = this.restTemplate.getForObject(DEPT_LIST_URL, List.class);
		return allDepts;
	}

	@RequestMapping(value = "/consumer/dept/add")
	public Object addDept(Dept dept) {
		Boolean flag = this.restTemplate.postForObject(DEPT_ADD_URL, dept, Boolean.class);
		return flag;
	}
}
